package cn.sunjinxin.trade.application.point.preorder;

import cn.sunjinxin.savior.ext.anno.ExtensionPoint;
import cn.sunjinxin.trade.domain.ability.PreorderAbility;
import cn.sunjinxin.trade.domain.model.ProductSku;
import cn.sunjinxin.trade.infrastructure.external.GatewayRpcService;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;

import javax.annotation.Resource;

/**
 * @author issavior
 */
@ExtensionPoint(bizCode = "gateway", scenario = "inventory")
public class GatewayPreorderPoint extends PreorderAbility {

    @Resource
    private GatewayRpcService gatewayRpcService;

    @Override
    public Boolean preorder(ProductSku request) {
        // 热点限流，以系统商ID维度
        try (Entry entry = SphU.entry("gateway_preorder", EntryType.IN, 1, request.getContractId())) {
            // 3. 系统商验单
            // 增加策略，滑动窗口，1分钟，接口超时20次，发送下架商品消息、告警、注册探针探活任务，5秒钟探活一次，
            // 如果探活成功，发送恢复商品上架消息（需要check最后一次下架的原因，只有系统商异常才会下架）
            return gatewayRpcService.preorder(request.getProductSkuId());
        } catch (Exception ignored) {
            return false;
        }
    }

    @Override
    public Boolean replenishment(ProductSku request) {
        return gatewayRpcService.cancelPreorder(request.getProductSkuId());
    }
}
